<?php
require_once ("person_controller.php");
class Customers extends Person_controller
{
	function __construct()
	{
		parent::__construct('customers');
	}
	
	function index()
	{
		if ($this->session->userdata('sort_customer_by') == false){ 
			$this->session->set_userdata('sort_customer_by', 'modify_date');
		} elseif ($this->input->post('order_by') != '' and $this->input->post('order_by') != $this->session->userdata('sort_customer_by')){
			$this->session->set_userdata('sort_customer_by', $this->input->post('order_by'));
		}
	
		$config['base_url'] = site_url('customers/index');
		$config['total_rows'] = $this->Customer->count_all();
		$config['per_page'] = $this->config->item('number_of_items_per_page') ? (int)$this->config->item('number_of_items_per_page') : 20; 
		$this->pagination->initialize($config);
		
		$data['controller_name']=strtolower(get_class());
		$data['form_width']=$this->get_form_width();
		$data['manage_table']=get_people_manage_table($this->Customer->get_all($config['per_page'], $this->uri->segment(3), $this->session->userdata('sort_customer_by')),$this);
		$data['order_by'] = $this->session->userdata('sort_customer_by');
		$this->load->view('people/manage',$data);
	}
	
	/*
	Returns customer table data rows. This will be called with AJAX.
	*/
	function search()
	{
		$search=$this->input->post('search');
		$data_rows=get_people_manage_table_data_rows($this->Customer->search($search,$this->config->item('number_of_items_per_page') ? (int)$this->config->item('number_of_items_per_page') : 20),$this);
		echo $data_rows;
	}
	
	/*
	Gives search suggestions based on what is being searched for
	*/
	function suggest()
	{
		$suggestions = $this->Customer->get_search_suggestions($this->input->get('term'),100);
		echo json_encode($suggestions);
	}
	
	/*
	Loads the customer edit form
	*/
	function view($customer_id=-1)
	{
		$data['person_info']=$this->Customer->get_info($customer_id);
		$this->load->view("customers/form",$data);
	}
	
	/*
	Inserts/updates a customer
	*/
	function save($customer_id=-1)
	{
		$person_data = array(
		'first_name'=>$this->input->post('first_name'),
		'last_name'=>$this->input->post('last_name'),
		'email'=>$this->input->post('email'),
		'phone_number'=>$this->input->post('phone_number'),
		'address_1'=>$this->input->post('address_1'),
		'address_2'=>$this->input->post('address_2'),
		'city'=>$this->input->post('city'),
		'state'=>$this->input->post('state'),
		'zip'=>$this->input->post('zip'),
		'country'=>$this->input->post('country'),
		'comments'=>$this->input->post('comments')
		);
		
		$employee_id=$this->Employee->get_logged_in_employee_info()->person_id;
		$emp_info=$this->Employee->get_info($employee_id);
		
		$customer_data=array(
		'nric' => $this->input->post('nric'),
		'title' => $this->input->post('title'),
		'designation' => $this->input->post('designation'),
		'nationality' => $this->input->post('nationality'),
		'store' => $this->input->post('store') == '' ? $this->Store->get_info($this->session->userdata('store_id'))->store_code : $this->input->post('store'),
		'birthday' => $this->input->post('birthday') == '' ? null : $this->input->post('birthday'),
		'create_date' => $this->input->post('create_date') == '' ?  date('Y-m-d H:i:s') : $this->input->post('create_date'),
		'modify_date' => date('Y-m-d H:i:s'),
		'modify_by' => $emp_info->first_name.' '.$emp_info->last_name,
		'company_name' => $this->input->post('company_name'),
		'preferred_contact' => $this->input->post('preferred_contact'),
		'account_number'=>$this->input->post('account_number')=='' ? null:$this->input->post('account_number'),
		'taxable'=>$this->input->post('taxable')=='' ? 0:1,
		);
		if($this->Customer->save($person_data,$customer_data,$customer_id))
		{
			if ($this->config->item('mailchimp_api_key'))
			{
				$this->Person->update_mailchimp_subscriptions($this->input->post('email'), $this->input->post('first_name'), $this->input->post('last_name'), $this->input->post('mailing_lists'));
			}
			//New customer
			if($customer_id==-1)
			{
				echo json_encode(array('success'=>true,'message'=>lang('customers_successful_adding').' '.
				$person_data['first_name'].' '.$person_data['last_name'],'person_id'=>$customer_data['person_id']));
			}
			else //previous customer
			{
				echo json_encode(array('success'=>true,'message'=>lang('customers_successful_updating').' '.
				$person_data['first_name'].' '.$person_data['last_name'],'person_id'=>$customer_id));
			}
		}
		else//failure
		{	
			echo json_encode(array('success'=>false,'message'=>lang('customers_error_adding_updating').' '.
			$person_data['first_name'].' '.$person_data['last_name'],'person_id'=>-1));
		}
	}
	
	/*
	This deletes customers from the customers table
	*/
	function delete()
	{
		$customers_to_delete=$this->input->post('ids');
		
		if($this->Customer->delete_list($customers_to_delete))
		{
			echo json_encode(array('success'=>true,'message'=>lang('customers_successful_deleted').' '.
			count($customers_to_delete).' '.lang('customers_one_or_multiple')));
		}
		else
		{
			echo json_encode(array('success'=>false,'message'=>lang('customers_cannot_be_deleted')));
		}
	}
	
	function excel()
	{
		$data = file_get_contents("import_customers.csv");
		$name = 'import_customers.csv';
		force_download($name, $data);
	}
	
	function excel_import()
	{
		$this->load->view("customers/excel_import", null);
	}
	
	/* added for excel expert */
	function excel_export() {
		$data = $this->Customer->get_all()->result_object();
		$this->load->helper('report');
		$rows = array();
		$row = array('Customer ID', 'Title', 'First Name', 'Last Name', 'E-Mail', 'Phone Number', 'Address 1', 'Address 2', 'City', 'State', 'Zip', 'Country', 'Comments', 'Account Number', 'Taxable', 'Company Name', 'Designation', 'Nationality', 'Birthday', 'Preferred Contact', 'Store', 'Create Date', 'Modify date', 'Modify by');
		$rows[] = $row;
		foreach ($data as $r) {
			$row = array(
				$r->nric,
				$r->title,
				$r->first_name,
				$r->last_name,
				$r->email,
				$r->phone_number,
				$r->address_1,
				$r->address_2,
				$r->city,
				$r->state,
				$r->zip,
				$r->country,
				$r->comments,
				$r->account_number,
				$r->taxable ? 'y' : '',
				$r->company_name,
				$r->designation,
				$r->nationality,
				$r->birthday,
				$r->preferred_contact,
				$r->store,
				$r->create_date,
				$r->modify_date,
				$r->modify_by	
			);
			$rows[] = $row;
		}
		
		$content = array_to_csv($rows);
		force_download('customers_export' . '.csv', $content);
		exit;
	}

	function do_excel_import()
	{
		$this->db->trans_start();
		
		$msg = 'do_excel_import';
		$failCodes = array();
		if ($_FILES['file_path']['error']!=UPLOAD_ERR_OK)
		{
			$msg = lang('items_excel_import_failed');
			echo json_encode( array('success'=>false,'message'=>$msg) );
			return;
		}
		else
		{
			if (($handle = fopen($_FILES['file_path']['tmp_name'], "r")) !== FALSE)
			{
				//Skip first row
				fgetcsv($handle);
				while (($data = fgetcsv($handle)) !== FALSE) 
				{
					$person_data = array(
					'first_name'=>$data[2],
					'last_name'=>$data[3],
					'email'=>$data[4],
					'phone_number'=>$data[5],
					'address_1'=>$data[6],
					'address_2'=>$data[7],
					'city'=>$data[8],
					'state'=>$data[9],
					'zip'=>$data[10],
					'country'=>$data[11],
					'comments'=>$data[12]
					);
					
					$customer_data=array(
					'nric'=>$data[0],
					'title'=>$data[1],
					'account_number'=>$data[13]=='' ? null:$data[13],
					'taxable'=>$data[14]=='' ? 0:1,
					'company_name' =>$data[15],
					'designation' =>$data[16],
					'nationality' =>$data[17],
					'birthday' =>$data[18]=='' ? null:$data[18],
					'preferred_contact' =>$data[19]=='' ? null:$data[19],
					'store' =>$data[20],
					'create_date' =>$data[21] == '' ? date('Y-m-d H:i:s') : $data[21] ,
					'modify_date' =>$data[22] == '' ? date('Y-m-d H:i:s') : $data[22],
					'modify_by' =>$data[23]
					);
					
					if(!$this->Customer->save($person_data,$customer_data))
					{	
						echo json_encode( array('success'=>false,'message'=>lang('customers_duplicate_account_id')));
						return;
					}
				}
			}
			else 
			{
				echo json_encode( array('success'=>false,'message'=>lang('common_upload_file_not_supported_format')));
				return;
			}
		}
		$this->db->trans_complete();
		echo json_encode(array('success'=>true,'message'=>lang('customers_import_successfull')));
	}
	
	/*Based on GoldlinkCRM_CSV_20120407.csv */
	function do_excel_import_goldlink()
	{
		$this->db->trans_start();
		
		$msg = 'do_excel_import';
		$failCodes = array();
		if ($_FILES['file_path']['error']!=UPLOAD_ERR_OK)
		{
			$msg = lang('items_excel_import_failed');
			echo json_encode( array('success'=>false,'message'=>$msg) );
			return;
		}
		else
		{
			if (($handle = fopen($_FILES['file_path']['tmp_name'], "r")) !== FALSE)
			{
				//Skip first row
				fgetcsv($handle);
				while (($data = fgetcsv($handle)) !== FALSE) 
				{
					
					$data[0] = $data[0] == '-' ? '' : $data[0];
					$data[1] = $data[1] == '-' ? '' : $data[1];
					$data[2] = $data[2] == '-' ? '' : $data[2];
					$data[3] = $data[3] == '-' ? '' : $data[3];
					$data[4] = $data[4] == '-' ? '' : $data[4];
					$data[5] = $data[5] == '-' ? '' : $data[5];
					$data[6] = $data[6] == '-' ? '' : $data[6];
					$data[7] = $data[7] == '-' ? '' : $data[7];
					$data[8] = $data[8] == '-' ? '' : $data[8];
					$data[9] = $data[9] == '-' ? '' : $data[9];
					$data[10] = $data[10] == '-' ? '' : $data[10];
					$data[11] = $data[11] == '-' ? '' : $data[11];
					$data[12] = $data[12] == '-' ? '' : $data[12];
					$data[13] = $data[13] == '-' ? '' : $data[13];
					$data[14] = $data[14] == '-' ? '' : $data[14];
					$data[15] = $data[15] == '-' ? '' : $data[15];
					$data[16] = $data[16] == '-' ? '' : $data[16];
					$data[17] = $data[17] == '-' ? '' : $data[17];
					$data[18] = $data[18] == '-' ? '' : $data[18];
					$data[19] = $data[19] == '-' ? '' : $data[19];
					$data[20] = $data[20] == '-' ? '' : $data[20];
					$data[21] = $data[21] == '-' ? '' : $data[21];
					$data[22] = $data[22] == '-' ? '' : $data[22];
					$data[23] = $data[23] == '-' ? '' : $data[23];
					
					$store = $data[0];
					if ($data[0] = '1001') $store = 'Goldlink';
					if ($data[0] = '1002') $store = 'Goldlink'; 
					if ($data[0] = '1003') $store = 'Zadi(SC)';
					if ($data[0] = '1004') $store = 'TE(SC)';
					if ($data[0] = '1005') $store = 'TE(RP)';
					if ($data[0] = '1006') $store = 'FLF(SC)';
					if ($data[0] = '1007') $store = 'Doro(TK)';
					if ($data[0] = '1008') $store = 'Goldlink';
					if ($data[0] = '1011') $store = 'FLF(TK)';
					if ($data[0] = '1012') $store = 'TE(CP)';
					if ($data[0] = '1015') $store = 'Zadi(OUB)';
					if ($data[0] = '1016') $store = 'Seiyu';
					if ($data[0] = '1019') $store = 'AteSeta';
					if ($data[0] = '1021') $store = 'Doro(Shaw)';
					if ($data[0] = '1022') $store = 'Doro(Rob)';
					if ($data[0] = '1023') $store = 'Doro(KT)';
					if ($data[0] = '1025') $store = 'TAT(CP)';
					if ($data[0] = '1026') $store = 'TAT(TAKA)';

					
					$phonenumber = $data[18] == '' ? $data[19] : $data[18];
					$phonenumber = $phonenumber == '' ? $data[14] : $phonenumber;

					$person_data = array(
					'first_name'=>$data[3],
					'last_name'=>$data[4],
					'email'=>$data[6],
					'phone_number'=> $phonenumber ,
					'address_1'=>$data[8] . ' ' . $data[9] . ' ' . $data[10] . ' ' . $data[11],
					'address_2'=>'',
					'city'=>'',
					'state'=>'',
					'zip'=>$data[13],
					'country'=>$data[12],
					'comments'=>$data[20]
					);
									
					$customer_data=array(
					'birthday'=>($data[5] == '' or $data[5] == '1900/01/01') ? null : $data[5],
					'store'=> $store,					
					'nric'=>$data[1],
					'title'=>$data[2],
					'account_number'=>null,
					'taxable'=>1,
					'company_name' => $data[15],
					'designation' => $data[16],
					'nationality' => $data[17],
					'create_date' => $data[21] == '' ? date('Y-m-d H:i:s') : $data[21] ,
					'modify_date' => $data[22] == '' ? date('Y-m-d H:i:s') : $data[22],
					'modify_by' => $data[23]
					);
					
					if(!$this->Customer->save($person_data,$customer_data))
					{	
						echo json_encode( array('success'=>false,'message'=>lang('customers_duplicate_account_id')));
						return;
					}
				}
			}
			else 
			{
				echo json_encode( array('success'=>false,'message'=>lang('common_upload_file_not_supported_format')));
				return;
			}
		}
		$this->db->trans_complete();
		echo json_encode(array('success'=>true,'message'=>lang('customers_import_successfull')));
	}
	
	function cleanup()
	{
		$this->Customer->cleanup();
		echo json_encode(array('success'=>true,'message'=>lang('customers_cleanup_sucessful')));
	}
	
	/*
	get the width for the add/edit form
	*/
	function get_form_width()
	{			
		return 550;
	}
}
?>